const express = require('express');
const mongoose = require('mongoose');
const router = express.Router();
const crypto = require('crypto');
const fs = require('fs');
const dayjs = require('dayjs');
const debug = require('debug')('a-sokio-yun:server');
const userMod = require('../../db/cloudControl/userMod');
const deviceShe = require('../../db/cloudControl/deviceSchema');
const { localDate, layuiMenu, publicPath, ppxxxkkk, adminName, maxLevel } = require('../../serverOpt');
const { deleteMongodb } = require('../../common/dbExports');

router.get('/getOneUserMenu', async function (req, res) {
	debug('获取指定用户的角色菜单接口');
	const { userName, userId } = req.session;
	if (!userId) {
		return res.json({ code: -1, msg: '请先登录' });
	}

	const userDoc = await userMod.findById(userId);
	if (!userDoc) {
		debug(`用户未找到(${userName})`);
		req.session.destroy();
		return res.end();
	}

	let newMenu = layuiMenu;
	if (userName == adminName) {
		//超级管理员
		let menuStr = fs.readFileSync(publicPath + '/common/menu.json', 'utf-8');
		let menuJson = JSON.parse(menuStr);
		newMenu.menuInfo[0].child = menuJson;
		return res.end(JSON.stringify(newMenu));
	} else {
		newMenu.menuInfo[0].child = userDoc.menuData;
		res.end(JSON.stringify(newMenu));
	}
});

router.post('/addUser', async function (req, res) {
	//添加的时候不可以跨级添加,所以父账号一定是当前登录账号
	const { userName, userId, userLevel } = req.session; //父账号信息
	// debug("userLevel", userLevel)
	if (!userName || !userId) {
		return res.json({ code: -1, msg: '请先登录' });
	}
	if (userLevel >= maxLevel) {
		return res.json({ code: -1, msg: '用户权限不足' });
	}
	const reqBody = req.body;
	reqBody.createTime = dayjs().format('YYYY-MM-DD HH:mm:ss');
	reqBody.parent = userId;
	reqBody.userPass = encrypt(reqBody.userPass);
	reqBody.userLevel = userLevel + 1;

	try {
		await userMod.create(reqBody);
		res.json({ code: 0, msg: '添加用户成功' });
	} catch (error) {
		console.error('添加用户错误', error);
		res.json({ code: -1, msg: `添加用户错误${error.message}请更换用户名` });
	}
});

router.post('/editUser', async function (req, res) {
	//编辑的时候可以跨级编辑,所以父账号不一定是当前登录账号
	const { userId, userLevel } = req.session; //父账号信息
	if (userLevel >= maxLevel) {
		return res.json({ code: -1, msg: '用户权限不足' });
	}

	try {
		await userMod.updateOne({ _id: req.body._id }, req.body);
		res.json({ code: 0, msg: '修改用户成功' });
	} catch (error) {
		console.error('修改用户错误', error);
		res.json({ code: -1, msg: '修改用户错误' + error.message });
	}
});

router.post('/changePass', async function (req, res) {
	const { userName, userId } = req.session;
	if (!userId) {
		return res.json({ code: -1, msg: '请先登录' });
	}
	const reqBody = req.body;
	const userPass = encrypt(reqBody.userPass);

	try {
		await userMod.updateOne({ _id: userId }, { userPass });
		req.session.destroy();
		res.json({ code: 0, msg: '修改密码成功' });
	} catch (error) {
		console.error('修改密码错误', error);
		res.json({ code: -1, msg: '修改密码错误' + error.message });
	}
});

router.post('/delUser', async function (req, res) {
	const { userId } = req.session;
	if (!userId) {
		return res.json({ code: -1, msg: '请先登录' });
	}
	//下面的_id是要删账号的_id
	const { _id } = req.body;
	const user = await userMod.findOne({ _id });
	console.log(user);
	try {
		if (await userMod.findOne({ parent: _id })) {
			debug('此用户有子账号,禁止删除');
			return res.json({ code: -1, msg: '此用户有子账号,禁止删除' });
		}
		await userMod.deleteOne({ _id });
		deleteMongodb(user.userName);
		debug('删除用户成功');
		res.json({ code: 0, msg: '删除用户成功' });
	} catch (error) {
		console.error('删除用户错误', error);
		res.json({ code: -1, msg: '删除用户错误' + error.message });
	}
});

router.post('/updateMaxDeviceNum', async (req, res) => {
	try {
		const { userName, parent, _id, maxDeviceNum } = req.body;
		if (!maxDeviceNum) {
			return res.json({ code: -1, msg: '请提供新的最大设备数' });
		}

		const parentUser = await userMod.findOne({ _id: parent }).lean();
		if (!parentUser) {
			return res.json({ code: -1, msg: '父用户不存在' });
		}

		const currentUser = await userMod.findOne({ _id }).lean();
		if (!currentUser) {
			return res.json({ code: -1, msg: '当前用户不存在' });
		}

		const parentSubUsers = await userMod.find({ parent: parentUser._id, _id: { $ne: _id } }).lean();
		const parentSubsSum = parentSubUsers.reduce((sum, user) => sum + user.maxDeviceNum, 0);
		console.log(parentSubsSum);
		const ParentDeviceMod = mongoose.model(`device_${parentUser.userName}`, deviceShe);
		const parentDeviceCount = await ParentDeviceMod.countDocuments();

		const subUsers = await userMod.find({ parent: _id }).lean();
		const subsSum = subUsers.reduce((sum, user) => sum + user.maxDeviceNum, 0);
		console.log(subsSum);
		const deviceMod = mongoose.model(`device_${userName}`, deviceShe);
		const deviceCount = await deviceMod.countDocuments();

		// 验证最低限制
		if (maxDeviceNum < deviceCount + subsSum) {
			return res.json({
				code: -1,
				msg: `可分配控数不能低于${deviceCount + subsSum}`,
			});
		}

		// 计算更新后总使用量
		const newTotal = parentDeviceCount + parentSubsSum + maxDeviceNum;
		console.log(parentDeviceCount, parentSubsSum, parentUser.maxDeviceNum);
		// 验证是否超过父级配额
		if (maxDeviceNum > parentUser.maxDeviceNum - parentDeviceCount - parentSubsSum) {
			const available = parentUser.maxDeviceNum - (parentDeviceCount + parentSubsSum);
			return res.json({
				code: -1,
				msg: `超过父级可分配配额，当前可用剩余为${available}，您最多可设置为${available}`,
			});
		}
		console.log(maxDeviceNum);
		// 执行更新操作
		await userMod.updateOne({ _id }, { $set: { maxDeviceNum } });

		res.json({ code: 0, msg: '更新成功' });
	} catch (error) {
		res.json({
			code: -1,
			msg: '更新最大设备数失败:' + error.message,
		});
	}
});

router.post('/getUserDeviceNum', async (req, res) => {
	try {
		const { userName, _id, parent } = req.body;
		const users = await userMod.find({}).lean();
		const usersMap = new Map(users.map((u) => [u._id.toString(), u]));

		// 辅助函数：创建设备模型
		const createDeviceModel = (userName) => {
			return mongoose.model(`device_${userName}`, deviceShe);
		};

		if (parent) {
			// 父级存在的情况（修改用户或占控）
			const parentUser = usersMap.get(parent);
			if (!parentUser) {
				return res.json({ code: -1, msg: 'Parent user not found' });
			}

			const parentDeviceMod = createDeviceModel(parentUser.userName);
			const deviceMod = createDeviceModel(userName);

			// 计算父级和当前用户的设备数
			const parentCount = (await parentDeviceMod.countDocuments()) || 0;
			const currentCount = (await deviceMod.countDocuments()) || 0;

			// 计算父级子用户的总maxDeviceNum
			const parentSubUsersSum = users.filter((u) => u.parent?.toString() === parentUser._id.toString()).reduce((sum, u) => sum + u.maxDeviceNum, 0);

			// 计算当前用户的子用户总maxDeviceNum
			const currentSubUsersSum = users.filter((u) => u.parent?.toString() === _id.toString()).reduce((sum, u) => sum + u.maxDeviceNum, 0);

			return res.json({
				code: 0,
				data: {
					isParentMaxDeviceNum: parentUser.maxDeviceNum,
					isParentDeviceNum: parentCount + parentSubUsersSum,
					isDeviceNum: currentCount + currentSubUsersSum,
				},
				msg: '查询成功',
			});
		} else {
			// 添加用户的情况
			const deviceMod = createDeviceModel(userName);
			const count = (await deviceMod.countDocuments()) || 0;

			// 计算当前用户的子用户总maxDeviceNum
			const subUsersSum = users.filter((u) => u.parent?.toString() === _id.toString()).reduce((sum, u) => sum + u.maxDeviceNum, 0);

			return res.json({
				code: 0,
				msg: '查询成功',
				data: { isDeviceNum: count + subUsersSum },
			});
		}
	} catch (error) {
		res.json({
			code: -1,
			msg: error.message,
		});
	}
});

router.get('/allUser', async function (req, res) {
	const { userName, userId } = req.session;
	if (!userId) {
		return res.json({ code: -1, msg: '请先登录' });
	}
	let searchDic = {};
	const users = await userMod.find(searchDic).lean(); // 使用 lean() 以获取普通 JS 对象数组
	if (!users) {
		return res.json({ code: -1, msg: '没有账号信息' });
	}
	for (let user of users) {
		if (user._id.toString() === userId) {
			user.parent = '-1'; // 修改parent字段，不保存到数据库
			break;
		}
	}

	for (const user of users) {
		user.isDeviceNum = 0;
		user.deviceNum = 0;
		const deviceMod = mongoose.model(`device_${user.userName}`, deviceShe);
		const count = await deviceMod.countDocuments();
		user.isDeviceNum += count ? count : 0;
		user.deviceNum += count ? count : 0;
		// console.log(user.userName,count,user.isDeviceNum)

		for (const u of users) {
			if (u.parent == user._id.toString()) {
				user.isDeviceNum += u.maxDeviceNum;
				// user.deviceNum += count;
			}
		}
	}
	// console.log(users)

	res.json({
		code: 0,
		msg: '获取成功',
		count: users.length,
		data: users,
	});
});

router.get('/getChildrenUsers', async function (req, res) {
	try {
		const { userName, userId } = req.session;
		const result = await userMod.find({ parent: userId });
		res.json({
			code: 0,
			msg: '获取成功',
			data: result,
		});
	} catch (error) {
		res.json({
			code: -1,
			msg: '获取失败'+error.message,
		});
	}
});

function encrypt(text) {
	const iv = crypto.randomBytes(16); // 初始化向量
	const cipher = crypto.createCipheriv('aes-256-cbc', ppxxxkkk, iv);
	let encrypted = cipher.update(text, 'utf8', 'hex');
	encrypted += cipher.final('hex');
	return { iv: iv.toString('hex'), encryptedData: encrypted };
}

module.exports = router;
